package cn.yunyichina.provider.register.service.impl;

import cn.yunyichina.provider.framework.annotation.validate.ValidateException;
import cn.yunyichina.provider.framework.annotation.validate.Validator;
import cn.yunyichina.provider.framework.common.PKGenerator;
import cn.yunyichina.provider.framework.dubbo.service.BaseService;
import cn.yunyichina.provider.framework.dubbo.service.CacheService;
import cn.yunyichina.provider.framework.dubbo.service.HisifaceService;
import cn.yunyichina.provider.framework.dubbo.service.MessageService;
import cn.yunyichina.provider.iface.entity.base.*;
import cn.yunyichina.provider.iface.entity.common.ResCommon;
import cn.yunyichina.provider.iface.entity.common.Response;
import cn.yunyichina.provider.iface.entity.hisiface.register.CancelRegisterVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.OrderRegisterVo;
import cn.yunyichina.provider.iface.entity.hisiface.register.OrderRegisterVoResponse;
import cn.yunyichina.provider.register.utils.RegUtil;
import cn.yunyichina.provider.register.vo.LockRegInfoVoOut;
import cn.yunyichina.provider.register.vo.OrderRegisterVoRequest;
import cn.yunyichina.utils.commons.DateUtils;
import cn.yunyichina.utils.convert.JsonUtils;
import cn.yunyichina.utils.convert.ObjectParser;
import cn.yunyichina.utils.log.Log;
import cn.yunyichina.utils.log.constant.LogParamType;
import cn.yunyichina.utils.log.constant.LogScene;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2016/12/1.
 */
@Service
public class RegRecordServiceImpl {
    private Logger logger = LoggerFactory.getLogger(RegRecordServiceImpl.class);

    @Autowired
    private  RegInsuranceServiceImpl regInsuranceService;

    @Resource
    private Properties yaml;
    @Autowired
    PayServiceImpl payService;

    /** 挂号锁号接口
     * yyt.register.reg.info.lock --> yyt.register.reg.record.lock
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response lockRegRecord(String data, String sessionId,String appId) throws Exception {
    	Response response = new Response();
//        logger.info("挂号锁号--->method:lockRegRecord,data:" + data + "！");
        //-------------------------------------------转换参数，并校验参数-------------------------------------
        OrderRegisterVoRequest requestVo = JsonUtils.parseObject(data, OrderRegisterVoRequest.class);
        Log.i(LogScene.REGISTER_DOCTOR_LOCK,"yyt.register.reg.record.lock", LogParamType.REQUEST,requestVo.getPatCardNo(), data);

        // 校验RequestVo的数据h
        try {
            Validator.getInstance().validate(requestVo);
        } catch (ValidateException ex) {
            logger.info(" 数据校验失败:" + ex.getMessage() + "|入参:" + data + "！");
            logger.error("error", ex);
            response.setResultCodeAndMessage("6001", "数据校验失败:" + ex.getMessage() + "！");
            return response;
        }
        //-----------------------------------------------------------------------------------------------------

        if(StringUtils.isNotBlank(requestVo.getReserveNo())){
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("org_code", requestVo.getHospitalCode());
            queryMap.put("reserve_no", requestVo.getReserveNo());
            queryMap.put("order_columns", "created_time desc");

            Response ordResponse = BaseService.callUnderlineFromInternal("",
                    "yyt.base.order.list.get", JsonUtils.toJsonString(queryMap));
//        logger.info("lockRegInfo, yyt.base.order.list ordResponse="+ JSON.toJSONString(ordResponse));
            if ("0".equals(ordResponse.getResultCode())) {
                List<OrderExtVo> list = JsonUtils.parseArray(ordResponse.getResult(), OrderExtVo.class);
                if (!CollectionUtils.isEmpty(list)) {
                    OrderExtVo reserveOrder = list.get(0);
                    if(reserveOrder.getPayStatus() == OrderExtVo.ORDER_PAY_STATUS_PAYED){
//                        logger.info("lockRegRecord,该预约号码" + requestVo.getReserveNo() + "已经支付，订单号为" + reserveOrder.getOrderNo());
                        Log.i(LogScene.REGISTER_DOCTOR_LOCK,"yyt.register.reg.record.lock", LogParamType.REQUEST,reserveOrder.getOrderNo(),
                                "该预约号码" + requestVo.getReserveNo() + "已经支付，订单号为" + reserveOrder.getOrderNo());
                        response.setResultCodeAndMessage("6008","该预约号码已经支付，订单号为" + reserveOrder.getOrderNo());
                        return response;
                    }
//                    预约未支付的再锁一次号
//                    if(reserveOrder.getPayStatus()< OrderExtVo.ORDER_PAY_STATUS_PAYED ){
//                       //存在未支付的订单，返回原订单
//                        logger.info("lockRegRecord,该预约号码" + requestVo.getReserveNo() + "存在未支付的订单，返回原订单" + reserveOrder.getOrderNo());
//                        LockRegInfoVoOut lockRegInfoVoOut = parseLocRegInfoVoOut(reserveOrder);
//                        response.setResultCodeAndMessage("0", "锁号成功");
//                        response.setResult(JsonUtils.toJsonString(lockRegInfoVoOut));
//                        return response;
//                    }
                }
            }
        }

        if(("stdxyxydefsyy".equals(requestVo.getHospitalCode()) || "stdxyxyfsdeyy".equals(requestVo.getHospitalCode()))
                && checkOneTimeReg(requestVo)){
            response.setResultCodeAndMessage("6009","同一天同一科室同一医生只能挂号一次");
            return response;
        }

        //判断是否重复订单
        Map reInvokeMap = checkReInvoke(requestVo);
        Boolean isReInvoke = (Boolean) reInvokeMap.get("reInvoke");
        if(isReInvoke){
            OrderExtVo reInvokeOrder = (OrderExtVo) reInvokeMap.get("order");
            if(!reInvokeOrder.getPlatformOrgAppCode().equals(appId)){
                logger.info("不同应用重复订单，原订单调用解锁" + reInvokeOrder.getOrderNo());
                Response unlockResp = unlockRegRecord("{\"order_no\":\"" + reInvokeOrder.getOrderNo() + "\"}",sessionId);
                logger.info("不同应用重复订单，原订单调用解锁,返回" + unlockResp);
                if(!unlockResp.getResultCode().equals("0")){
                    response.setResultCodeAndMessage("6006", "原订单解锁失败");
                    return response;
                }
            }else {
                logger.info("lockRegRecord，重复订单" + reInvokeOrder.getOrderNo());
                LockRegInfoVoOut lockRegInfoVoOut = parseLocRegInfoVoOut(reInvokeOrder);
                response.setResultCodeAndMessage("0", "锁号成功");
                response.setResult(JsonUtils.toJsonString(lockRegInfoVoOut));
                return response;
            }
        }

        // 查询医院信息 需要产出hospitalId hospitalName branchId branchCode
        String hospitalCode = requestVo.getHospitalCode();
        String branchCode = requestVo.getBranchCode();
        String hospitalId="";
        String hospitalName="";
        String branchId = requestVo.getBranchId();
        String branchName= requestVo.getBranchName();
        String hisCode = branchCode;

        Org org = BaseService.getBaseClient().getOrgByCode(hospitalCode);
        if (org == null) {
            response.setResultCodeAndMessage("6000", "没有org_code对应的机构信息:" + hospitalCode + "！");
            return response;
        }
        hospitalId = org.getId();
        hospitalName = org.getOrgName();

//        if(StringUtils.isNotBlank(branchCode)) {
//            //查找分院，转换成his的分院编码，表sys_org_setting
//            OrgSettingVo orgSettingVo = new OrgSettingVo();
//            orgSettingVo.setHospitalCode(hospitalCode);
//            orgSettingVo.setBranchCode(branchCode);
//            ResCommon orgSettingRes= BaseService.getBaseClient().getOrgSettingList(orgSettingVo);
//            if (orgSettingRes == null || !"0".equals(orgSettingRes.getResultCode())) {
//                response.setResultCodeAndMessage("6000", "没有分院branchCode对应的机构信息:" + branchCode + "！");
//                return response;
//            }
//            List<OrgSettingVoResponse> orgSettingList = (List<OrgSettingVoResponse>) orgSettingRes.getResult();
//            if (CollectionUtils.isEmpty(orgSettingList)) {
//                response.setResultCodeAndMessage("6004", "不存在[hospitalCode:" + hospitalCode + "]对应的设置信息！");
//                return response;
//            }
//            OrgSettingVoResponse setting = orgSettingList.get(0);
//            branchId = setting.getBranchId();
//            branchName = setting.getBranchName();
//            hisCode = setting.getHisCode();
//        }

        //判断是预约，还是当天的
        int days = DateUtils.daysBetween(DateUtils.today(), requestVo.getScheduleDate());
        String regType;
        if (days == 0) {
            regType = "1";
        } else if (days > 0) {
            regType = "2";
        } else {
            response.setResultCodeAndMessage("6005","您的号源已过期");
            return response;
        }

        if("stszxyy".equals(hospitalCode) && regType.equals("1")){
            //汕头中心当天挂号特殊规则判断
            String now = new SimpleDateFormat("HH:mm").format(new Date());
            String middleTime = "12:00";
            if(middleTime.compareTo(requestVo.getBeginTime()) > 0 && now.compareTo("07:00") > 0){
                response.setResultCodeAndMessage("6005","上午7点后不能预约上午的号源");
                return response;
            }
            if( now.compareTo("14:00") > 0){
                response.setResultCodeAndMessage("6005","下午14点后不能预约当天号源");
                return response;
            }
        }

        //----------------------------------------------请求his锁号----------------------------------------------------
        String orderNo = CacheService.generateOrderNum(1, 1);
        OrderRegisterVoResponse orderResponse = null;
        boolean needLock = true ;
        if("2".equals(RegUtil.getRule(hospitalCode,RegUtil.RESERVE_NEED_LOCK,"1"))){
            needLock = false;
        }
        if(needLock) {
            OrderRegisterVo orderRegisterVo = new OrderRegisterVo();
            BeanUtils.copyProperties(requestVo, orderRegisterVo);
            orderRegisterVo.setBranchCode(hisCode);
            orderRegisterVo.setYytOrdNum(orderNo);
            orderRegisterVo.setOrderNo(requestVo.getReserveNo());
            orderRegisterVo.setRegType(regType);

            if ("1".equals(orderRegisterVo.getIsInsurance())) {
                //医保时候，此项为社保诊疗费
                orderRegisterVo.setTreatFee(requestVo.getSsTreatFee());
            }

            JSONObject hisReqExtra = requestVo.getExtraParams()==null?new JSONObject():requestVo.getExtraParams();
            hisReqExtra.put("pat_mobile",requestVo.getPatMobile());//锁号增加手机号
            hisReqExtra.put("pat_name",requestVo.getPatName());
            hisReqExtra.put("pat_sex",requestVo.getPatSex());
            hisReqExtra.put("pat_card_no",requestVo.getPatCardNo());
            hisReqExtra.put("pat_card_type",requestVo.getPatCardType());
            hisReqExtra.put("pat_id_no",requestVo.getPatIdNo());
            hisReqExtra.put("pat_id_type",requestVo.getPatIdType());
            hisReqExtra.put("owner_ship",requestVo.getOwnership());

            hisReqExtra.put("treat_fee",requestVo.getTreatFee());//福田中医院需求
            hisReqExtra.put("ss_treat_fee",requestVo.getSsTreatFee());
            if(requestVo.getHospitalCode().indexOf("szsykyy") >=0 && appId.equals("yyt48fe49dbe6eb1cee")){
                hisReqExtra.put("channel","1");
            }else if(requestVo.getHospitalCode().indexOf("szsykyy") >=0 && appId.equals("yytcda5b2de00d8717c")){
                hisReqExtra.put("channel","2");
            }

            if (hisReqExtra != null ) {
                orderRegisterVo.setExtendParams(hisReqExtra.toJSONString().replace("insurance_card_no", "medicare_card_no"));
            }
            ResCommon<OrderRegisterVoResponse> hisResponse = HisifaceService.getHisifaceClient().orderRegister(orderRegisterVo);
//            logger.info("lockRegRecord,orderRegister requst={},hisResponse={}", JSONObject.toJSONString(orderRegisterVo), JSONObject.toJSONString(hisResponse));
            Log.i(LogScene.REGISTER_DOCTOR_LOCK,"orderRegister", LogParamType.REQUEST,orderRegisterVo.getOrderNo(),JSONObject.toJSONString(orderRegisterVo));
            Log.i(LogScene.REGISTER_DOCTOR_LOCK,"orderRegister", LogParamType.RESPONSE,orderRegisterVo.getOrderNo(),JSONObject.toJSONString(hisResponse));
            if (!"0".equals(hisResponse.getResultCode())) {
                response.setResultCodeAndMessage(hisResponse.getResultCode(), "调用锁号接口失败:" + hisResponse.getResultMessage() + "！");
                return response;
            }
            orderResponse = hisResponse.getResult();
        }
        //------------------------------------------------------------------------------------------------------------

        //-----------------------------------------------构建订单--------------------------------------------------
        OrderExtVo order = new OrderExtVo();

        Map<String, String> map = new HashMap<String, String>();
        map.put("org_app_code", appId);
        Response baseRes = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.orgapp.get", JsonUtils.toJsonString(map));
        if("0".equals(baseRes.getResultCode())) {
            JSONObject o = JSONObject.parseObject(baseRes.getResult());
            order.setPlatformId(o.getString("org_id"));
            order.setPlatformName(o.getString("org_name"));
            order.setPlatformCode(o.getString("org_code"));
            order.setPlatformOrgAppCode(o.getString("org_app_code"));//平台应用编码
        }else{
            response.setResultCodeAndMessage("6000", "没有对应app_id的应用:" + appId + "！");
            return response;
        }


        order.setId(PKGenerator.generateId());
        order.setOrderNo(orderNo);
        order.setOrgId(hospitalId);
        order.setOrgCode(hospitalCode);
        order.setOrgName(hospitalName);
        order.setBranchId(branchId);
        order.setBranchCode(branchCode);
        order.setBranchName(branchName);

        order.setOrderStatusCreate();
        order.setPayStatusAccess();
        order.setOrderTypeRegister();
        order.setHisOrderNo(orderResponse==null?"":orderResponse.getHisOrdNum());
        order.setOpenId(requestVo.getOpenId());
        order.setPayAppId(requestVo.getAppId());
        order.setUserId(requestVo.getUserId());
        if(StringUtils.isNotBlank(requestVo.getPayMode())){
            order.setPayMode(Short.parseShort(requestVo.getPayMode()));
        }else{
            order.setPayMode(Short.parseShort(requestVo.getOrderMode()));
        }
        order.setUserName(requestVo.getPatName());
        order.setUserAddress(requestVo.getPatAddress());
        order.setMedicalCardNo(requestVo.getPatCardNo());
        order.setMedicalCardType(requestVo.getPatCardType() != null ? Short.parseShort(requestVo.getPatCardType()) : (short) 1);
        order.setPayUserId(requestVo.getPatId());
        order.setIdCardNo(requestVo.getPatIdNo());
        order.setIdCardType(requestVo.getPatIdType() != null ? Short.parseShort(requestVo.getPatIdType()) : (short) 1);
        order.setUserMobile(requestVo.getPatMobile());
        short sex =StringUtils.isNotBlank(requestVo.getPatSex()) ? Short.parseShort(requestVo.getPatSex()) : (short) 3;
        if(sex == 3 && requestVo.getPatIdNo()!=null&&requestVo.getPatIdNo().length()==18 ){
            String sCardNum = requestVo.getPatIdNo().substring(16, 17);
            if (Integer.parseInt(sCardNum) % 2 != 0) {
                sex = 1;
            } else {
                sex = 2;
            }
        }
        order.setUserSex(sex);
        order.setDoctorCode(requestVo.getDoctorCode());
        order.setDoctorName(requestVo.getDoctorName());
        order.setDoctorTitle(requestVo.getDoctorTitle());
        order.setDeptCode(requestVo.getDeptCode());
        order.setDeptName(requestVo.getDeptName());
        order.setCreatedTime(DateUtils.dateToString(new Date()));
        order.setIsInsurance(Short.valueOf(requestVo.getIsInsurance()));
        order.setScheduleTime(requestVo.getScheduleDate());
        order.setOrderTime(StringUtils.isNotBlank(requestVo.getOrderTime())?requestVo.getOrderTime():order.getCreatedTime());//下单时间
        order.setScheduleTime(requestVo.getScheduleDate());
        order.setReserveNo(requestVo.getReserveNo());

        Map<String,Object> extraParams = new HashMap<>();
        extraParams.put("begin_time",requestVo.getBeginTime());
        extraParams.put("end_time",requestVo.getEndTime());
        extraParams.put("work_id",requestVo.getWorkId());
        String payTimeout = RegUtil.getRule(order.getOrgCode(),RegUtil.PAYMENT_TIMEOUT_TIME,"10");
        extraParams.put("pay_timeout_time",payTimeout);//支付超时时间

        String insurance_order_no="";
        if(orderResponse !=null && StringUtils.isNotBlank(orderResponse.getExtendParams())){
        	JSONObject extendParamsObject=JSON.parseObject(orderResponse.getExtendParams());
        	if(extendParamsObject.containsKey("insurance_ord_num")){
        		insurance_order_no=extendParamsObject.getString("insurance_ord_num");
        	}
        }
        extraParams.put("insurance_order_no", insurance_order_no);
        extraParams.put("reg_category",orderResponse==null?"":orderResponse.getRegCategory());
        if(StringUtils.isNotBlank(orderResponse.getVisitLocation())){
            extraParams.put("visit_address",orderResponse.getVisitLocation());
        }
        if(StringUtils.isNotBlank(orderResponse.getSerialNum())){
            extraParams.put("serial_num",orderResponse.getSerialNum());
        }

        //设置医保参数
        JSONObject reqExtend = requestVo.getExtraParams();
        if(reqExtend != null) {
            order.setInsuranceCardNo(reqExtend.getString("insurance_card_no "));
            extraParams.put("medical_card_no",reqExtend.getString("medical_card_no"));
            extraParams.put("computer_no",reqExtend.getString("computer_no"));
            //医保卡加密串、密码、参保类型
            if(StringUtils.isNotBlank(reqExtend.getString("insurance_card_pwd"))){
                extraParams.put("insurance_card_pwd",reqExtend.getString("insurance_card_pwd"));
            }
            if(StringUtils.isNotBlank(reqExtend.getString("insurance_card_encrypt"))){
                extraParams.put("insurance_card_encrypt",reqExtend.getString("insurance_card_encrypt"));
            }
            if(StringUtils.isNotBlank(reqExtend.getString("insurance_type"))){
                extraParams.put("insurance_type",reqExtend.getString("insurance_type"));
            }
        }
        boolean isGongyi = false;//省二是否公医不用支付
        //医保锁号his返回的业务扩展参数
        String hisOutExtendStr = orderResponse==null?"":orderResponse.getExtendParams();
        if(StringUtils.isNotBlank(hisOutExtendStr)){
            JSONObject hisOutExtend = JSONObject.parseObject(hisOutExtendStr);
            extraParams.put("insurance_order_no",hisOutExtend.getString("insurance_ord_num"));
            extraParams.put("medical_org_code",hisOutExtend.getString("yljgbm"));
            extraParams.put("operator_code",hisOutExtend.getString("czybm"));
            extraParams.put("operator_name",hisOutExtend.getString("czyxm"));
            extraParams.put("cancel_serial_no",hisOutExtend.getString("cancel_serial_no"));
            extraParams.put("cancel_bill_no",hisOutExtend.getString("cancel_bill_no"));
            if(StringUtils.isNotBlank(hisOutExtend.getString("s_s_info"))){
                extraParams.put("s_s_info",hisOutExtend.getString("s_s_info"));
            }
            if("1".equals(hisOutExtend.getString("is_gongyi"))){
                isGongyi = true ;
            }
        }


        //设置医院返回的order信息到扩展参数
        addHisOrderInfo(orderResponse,extraParams,requestVo.getRegFee(),requestVo.getTreatFee());

        int realRegFee = ObjectParser.toInteger(extraParams.get("real_reg_fee"));
        int realTreatFee = ObjectParser.toInteger(extraParams.get("real_treat_fee"));
        extraParams.put("ss_treat_fee",requestVo.getSsTreatFee());
        if("1".equals(requestVo.getIsInsurance())){
            int ssTreatFee =ObjectParser.toInteger(requestVo.getSsTreatFee());
            order.setPayAmount(realRegFee);//银行卡付的钱
            order.setTotalAmount(realRegFee + ssTreatFee);//医保卡扣的钱
            order.setAccountAmount(ssTreatFee);
            order.setMedicareAmount(0);
            order.setInsuranceAmount(ssTreatFee);
            order.setInsuranceMode((short) 1);//insurance_mode==null   自费  insurance_mode=1   支付宝/微信医保支付 nsurance_mode=4   医院医保结算
        }else {
            int payAmount = realRegFee + realTreatFee ;// for test
            order.setPayAmount(payAmount);
            order.setTotalAmount(payAmount);
            order.setAccountAmount(0);
            order.setMedicareAmount(0);
            order.setInsuranceAmount(0);
        }
        order.setExtraParams(JSON.toJSONString(extraParams));
        if(StringUtils.isNotBlank(orderResponse.getOrderNo())){
            order.setReserveNo(orderResponse.getOrderNo());
        }

        String onlinePaymentControl;
        boolean needAckPayOrder = false ;//是否需要写单
        if( "2".equals(regType)){
            //预约挂号 是否在线支付控制规则
            onlinePaymentControl = RegUtil.getRule(order.getOrgCode(),RegUtil.ONLINE_PAYMENT_CONTROL_APPOINTMENT,"1");
        }else {
            onlinePaymentControl = RegUtil.getRule(order.getOrgCode(), RegUtil.ONLINE_PAYMENT_CONTROL, "1");
        }

        if("2".equals(onlinePaymentControl) || ("2".equals(regType) && "1".equals(requestVo.getIsInsurance()))
        || isGongyi || "1".equals(requestVo.getIsNotPay())) {//医保预约的也不用支付
            order.setOrderStatusSuccess();//不用支付，更改订单状态为成功，不用调写单
            order.setOnlinePaymentControl("2");
        }else if("1".equals(onlinePaymentControl)){
            if((realRegFee + realTreatFee) == 0){
                if("1".equals(requestVo.getIsInsurance())){
                    order.setOnlinePaymentControl("5");//金额为0，且是医保
                }else{
                    needAckPayOrder = true;//金额为0的自费单，需要调写单
                    order.setOnlinePaymentControl("4");
                }
            }else{
                order.setOnlinePaymentControl("1");
            }
        }else if("3".equals(onlinePaymentControl)){
            order.setOnlinePaymentControl("3");
        }else{
            order.setOnlinePaymentControl("1");
        }

        List<OrderExtVo> orders = new ArrayList<OrderExtVo>();
        orders.add(order);
        logger.info("lockRegRecord-> batchInsert=" + JSON.toJSONString(orders));
        BaseService.callUnderlineFromInternal(sessionId,
                "yyt.base.order.out.add", JsonUtils.toJsonString(orders));

        //河源人民0元挂号,调解锁,返回给前端OnlinePaymentControl为2，前端提示到线下挂号
        if("hysrmyy".equals(order.getOrgCode()) && order.getPayAmount() == 0 ){
            order.setOnlinePaymentControl("2");
            needAckPayOrder = false ;
            unlockRegRecord("{\"order_no\":\"" + order.getOrderNo() + "\"}",sessionId);
        }

        if(needAckPayOrder){
            //规则配置成需要支付，金额为0的自费订单，需要调写单接口
            String payData = "{\"yyt_order_no\":\"" + order.getOrderNo() +"\"}";
            payService.ackPayRegRecord(payData,sessionId);
        }
        //-----------------------------------------------------------------------------------------------------------

        //------------------------------------------------------- 构造返回的结构--------------------------------------
        LockRegInfoVoOut lockRegInfoVoOut = parseLocRegInfoVoOut(order);
        response.setResultCodeAndMessage("0", "锁号成功");
        response.setResult(JsonUtils.toJsonString(lockRegInfoVoOut));
        logger.info("lockRegRecord, response=" + JSONObject.toJSONString(lockRegInfoVoOut));
        //-------------------------------------------------------------------------------------------------------------

        String url = yaml.getProperty("order.reg.url") + "order_no=" + order.getOrderNo() + "&app_code=" + order.getPlatformOrgAppCode() + "&open_id=" + order.getOpenId() + "&app_id=" + order.getPayAppId();
        if(isGongyi){
            sendGongyiMsg(order,extraParams,url);
        }else if("2".equals(order.getOnlinePaymentControl()) && !needAckPayOrder) {// 不用支付的 预约成功发送消息
            try {
                String method = "yyt.message.msg.template.send";
                String sexMsg = "";
                if (1 == order.getUserSex()) {
                    sexMsg = "男";
                } else if (2 == order.getUserSex()) {
                    sexMsg = "女";
                }
                String scheduleTime = order.getScheduleTime();
                if (scheduleTime != null && scheduleTime.length() > 10) {
                    scheduleTime = scheduleTime.substring(0, 10);

                }
                scheduleTime += " " + extraParams.get("begin_time") + "-" + extraParams.get("end_time");
                Map<String, Object> dataMap = new HashedMap();
                dataMap.put("user_type", "2");
                dataMap.put("to_user", order.getOpenId());
                dataMap.put("order_no", order.getOrderNo());
                if (order.getPayMode() !=null && String.valueOf(order.getPayMode()).startsWith("1")){
                    dataMap.put("platform_type", "1");
                } else  if (order.getPayMode() !=null && String.valueOf(order.getPayMode()).startsWith("2")) {
                    dataMap.put("platform_type", "2");
                }
                // dataMap.put("platform_type","2");
                dataMap.put("org_app_code", order.getPlatformOrgAppCode());
                dataMap.put("org_code", order.getOrgCode());
                dataMap.put("template_code", "21012");
                Map<String, Object> msgContent = new HashedMap();
                msgContent.put("first", "您好，您已经挂号成功。");
                String remark = "";
                if("stszxyy".equals(order.getOrgCode())){
                    JSONObject hisOutExtend = JSONObject.parseObject(hisOutExtendStr);
                    if(hisOutExtend != null && StringUtils.isNotBlank(hisOutExtend.getString("advice_time"))){
                        scheduleTime = hisOutExtend.getString("advice_time") + "-" + hisOutExtend.getString("invalid_time");
                    }
                    if("1".equals(dataMap.get("platform_type"))) {
                        msgContent.put("patientName", order.getUserName());
                        msgContent.put("patientSex", sexMsg);
                        msgContent.put("hospitalName", order.getOrgName());
                        msgContent.put("department", order.getDeptName());
                        msgContent.put("doctor", order.getDoctorName());
                        msgContent.put("seq", order.getHisOrderNo() == null ? "" : order.getHisOrderNo());
                    }else if("2".equals(dataMap.get("platform_type"))) {
                        msgContent.put("keyword1", order.getUserName());
                        msgContent.put("keyword2", sexMsg);
                        msgContent.put("keyword3", order.getDeptName());
                        msgContent.put("keyword4", order.getDoctorName());
                        msgContent.put("keyword5", scheduleTime);
                    }
                    remark = "就诊地址:" + (extraParams.get("visit_address") == null ? "" : extraParams.get("visit_address"))
                            + "\n就诊时间:" + scheduleTime
                            + "\n注意：就诊当天，请在就诊时间前到分诊台报到。";
                }else if("jmsjhqrmyy".equals(order.getOrgCode())){
                    if("1".equals(dataMap.get("platform_type"))) {
                        msgContent.put("keyword1", order.getUserName());
                        msgContent.put("keyword2", sexMsg);
                        msgContent.put("keyword3", order.getDeptName());
                        msgContent.put("keyword4", order.getDoctorName());
                        msgContent.put("keyword5", scheduleTime);
                        remark = "门诊ID:" + order.getMedicalCardNo()
                                 + "\n订单号:" + order.getOrderNo()
                                + "\n流水号:" + (order.getHisOrderNo() == null ? "" : order.getHisOrderNo())
                                + "\n就诊说明:" + (extraParams.get("visit_desc") == null ? "" : extraParams.get("visit_desc"));
                        if (StringUtils.isNotBlank(order.getReserveNo())) {
                            remark += "\n预约号码:" + order.getReserveNo();
                        }
                    }else if("2".equals(dataMap.get("platform_type"))) {
                        msgContent.put("keyword1", order.getUserName());
                        msgContent.put("keyword2", sexMsg);
                        msgContent.put("keyword3", order.getDeptName());
                        msgContent.put("keyword4", order.getDoctorName());
                        msgContent.put("keyword5", scheduleTime);
                        remark = "门诊ID:" + order.getMedicalCardNo()
                                + "\n订单号:" + order.getOrderNo()
                                + "\n流水号:" + (order.getHisOrderNo() == null ? "" : order.getHisOrderNo())
                                + "\n就诊说明:" + (extraParams.get("visit_desc") == null ? "" : extraParams.get("visit_desc"));
                        if (StringUtils.isNotBlank(order.getReserveNo())) {
                            remark += "\n预约号码:" + order.getReserveNo();
                        }
                    }
                }else {
                    msgContent.put("keyword1", order.getUserName());
                    msgContent.put("keyword2", sexMsg);
                    msgContent.put("keyword3", order.getDeptName());
                    msgContent.put("keyword4", order.getDoctorName());
                    msgContent.put("keyword5", scheduleTime);
                    remark = "排队号:" + (extraParams.get("serial_num") == null ? "" : extraParams.get("serial_num"))
                            + "\n订单号:" + order.getOrderNo();
                    if (order.getReceiptNum() != null) {
                        remark += "\n发票流水号:" + (order.getReceiptNum() == null ? "" : order.getReceiptNum());
                    }
                    if("szszyy".equals(order.getOrgCode())){
                        //深中登记号改成病人卡号
                        remark += "\n病人卡号:" + (order.getMedicalCardNo() == null ? "" : order.getMedicalCardNo());
                    }else if (order.getHisOrderNo() != null) {
                        remark += "\n登记号:" + (order.getHisOrderNo() == null ? "" : order.getHisOrderNo());
                    }
                    if (extraParams.get("visit_address") !=null){
                        remark += "\n就诊地址:" + (extraParams.get("visit_address") == null ? "" : extraParams.get("visit_address"));
                    }
                    if (extraParams.get("visit_desc") != null) {
                        remark += "\n就诊说明:" + (extraParams.get("visit_desc") == null ? "" : extraParams.get("visit_desc"));
                    }
                    if (StringUtils.isNotBlank(order.getReserveNo())) {
                        remark += "\n预约号码:" + order.getReserveNo();
                    }

                }

                if ("szsdermyy".equals(order.getOrgCode())){
                    msgContent.put("first", "您好，您已经预约成功。");
                    if("2".equals(RegUtil.getRegType(order.getScheduleTime()))){
                        //深二自费、医保预约消息提示
                        remark += "\n就诊卡:" + (order.getMedicalCardNo()== null ? "":order.getMedicalCardNo()) ;
                        remark += "\n若您已支付，系统会在就诊时段开始时间前两小时自动取号，可通过支付宝预约取号获取就诊信息后直接就诊；若您未支付，请于就诊时段前30分钟通过支付宝或窗口凭预约号取号；不能及时就诊请于就诊时段前2小时取消，如因个人原因超时未取号不得退号退款。本院停车位紧张，请乘坐公共交通工具就诊";
                    }
                }

                msgContent.put("remark", remark);
                dataMap.put("msg_content", JSON.toJSONString(msgContent));

                dataMap.put("url", url);

                Response messageResponse = MessageService.callHumpFromInternal(method, JsonUtils.toJsonString(dataMap));
//                logger.info("不用支付的 预约成功发送消息, 订单号" + order.getOrderNo() + ", 调用message模块, request={}，response={}",
//                        JsonUtils.toJsonString(dataMap), JsonUtils.toJsonString(messageResponse));
                Log.i(LogScene.REGISTER_DOCTOR_LOCK,"yyt.register.reg.record.lock", LogParamType.REQUEST,order.getOrderNo(),
                        "不用支付的 预约成功发送消息,调用message模块, request=" +JsonUtils.toJsonString(dataMap));
                Log.i(LogScene.REGISTER_DOCTOR_LOCK,"yyt.register.reg.record.lock", LogParamType.RESPONSE,order.getOrderNo(),
                        "不用支付的 预约成功发送消息,调用message模块, response=" +JsonUtils.toJsonString(messageResponse));

            } catch (Exception e) {
                logger.error("不用支付的 预约成功发送消息, 消息推送失败:", e);
            }

            if("yytc06514ff54dbe32d".equals(order.getPlatformOrgAppCode())){
                //云医通插入消息记录
                Map<String,Object> yytMap = new HashedMap();
                yytMap.put("id",PKGenerator.generateId());
                yytMap.put("org_id", order.getOrgId());
                yytMap.put("org_name",order.getOrgName());
                yytMap.put("org_code",order.getOrgCode());
                yytMap.put("user_id",order.getUserId());
                yytMap.put("user_name",order.getUserName());
//            yytMap.put("library_template_code",msgCenter.getTemplateId());
                yytMap.put("msg_title","挂号成功通知");
                yytMap.put("is_read",1);

                Map<String,Object> contentMap = new HashedMap();
                List<Map<String,String>> msgTemplateContents = new ArrayList<>();
                Map<String,String> firstMap = new HashedMap();
                firstMap.put("keyword","first");
                firstMap.put("note","");
                firstMap.put("value","您好，您已经挂号成功。");
                msgTemplateContents.add(firstMap);

                Map<String,String> k1Map = new HashedMap();
                k1Map.put("keyword","姓名");
                k1Map.put("note","");
                k1Map.put("value",order.getUserName());
                msgTemplateContents.add(k1Map);

                Map<String,String> k2Map = new HashedMap();
                k2Map.put("keyword","医院");
                k2Map.put("note","");
                k2Map.put("value",order.getOrgName());
                msgTemplateContents.add(k2Map);

                Map<String,String> k3Map = new HashedMap();
                k3Map.put("keyword","挂号科室");
                k3Map.put("note","");
                k3Map.put("value",order.getDeptName());
                msgTemplateContents.add(k3Map);

                Map<String,String> k4Map = new HashedMap();
                k4Map.put("keyword","挂号医生");
                k4Map.put("note","");
                k4Map.put("value",order.getDoctorName());
                msgTemplateContents.add(k4Map);

                Map<String,String> k5Map = new HashedMap();
                k5Map.put("keyword","订单号");
                k5Map.put("note","");
                k5Map.put("value",order.getOrderNo());
                msgTemplateContents.add(k5Map);

                if(extraParams.get("serial_num") != null) {
                    Map<String, String> k6Map = new HashedMap();
                    k6Map.put("keyword", "排队号");
                    k6Map.put("note", "");
                    k6Map.put("value", (String) extraParams.get("serial_num"));
                    msgTemplateContents.add(k6Map);
                }
                if(extraParams.get("visit_address") != null) {
                    Map<String, String> k7Map = new HashedMap();
                    k7Map.put("keyword", "就诊地址");
                    k7Map.put("note", "");
                    k7Map.put("value", (String) extraParams.get("visit_address"));
                    msgTemplateContents.add(k7Map);
                }

//                logger.info("~~~~~~~msgTemplateContents=" + JsonUtils.toJsonString(msgTemplateContents));
                contentMap.put("msgTemplateContents", msgTemplateContents);

                List<Map<String,String>> msgTemplateFunctions = new ArrayList<>();
                Map<String,String> funcMap = new HashedMap();
                funcMap.put("functionCode","location='" +url + "'" );
                funcMap.put("functionName","点击查看挂号详情");
                msgTemplateFunctions.add(funcMap);

                contentMap.put("msgTemplateFunctions",msgTemplateFunctions);
                yytMap.put("msg_content",JsonUtils.toJsonString(contentMap));
                yytMap.put("created_time",DateUtils.dateToString(new Date()));

                Response messageResponse = MessageService.callHumpFromInternal("yyt.message.messagehistory.add",JsonUtils.toJsonString(yytMap));
                logger.info("订单号" + order.getOrderNo() + ", 调用message模块,yyt.message.messagehistory.add request={}，response={}",
                        JsonUtils.toJsonString(yytMap),JsonUtils.toJsonString(messageResponse));

            }
        }

        return response;
    }

    /**
     * 发送公医取号消息
     * @param order
     * @param extraParams
     * @param url
     */
    private void sendGongyiMsg(OrderExtVo order, Map<String, Object> extraParams, String url) {
        if("yytc06514ff54dbe32d".equals(order.getPlatformOrgAppCode())){
            //云医通插入消息记录
            Map<String,Object> yytMap = new HashedMap();
            yytMap.put("id",PKGenerator.generateId());
            yytMap.put("org_id", order.getOrgId());
            yytMap.put("org_name",order.getOrgName());
            yytMap.put("org_code",order.getOrgCode());
            yytMap.put("user_id",order.getUserId());
            yytMap.put("user_name",order.getUserName());
//            yytMap.put("library_template_code",msgCenter.getTemplateId());
            yytMap.put("msg_title","预约成功通知");
            yytMap.put("is_read",1);

            Map<String,Object> contentMap = new HashedMap();
            List<Map<String,String>> msgTemplateContents = new ArrayList<>();
            Map<String,String> firstMap = new HashedMap();
            firstMap.put("keyword","first");
            firstMap.put("note","");
            firstMap.put("value","您好，" + order.getUserName() + "(卡号：" + order.getMedicalCardNo() + ")已预约成功（未取号）,"
            + "订单号：" + order.getOrderNo() + ",请提前半小时到门诊大厅挂号窗口缴费取号，如需退号请在就诊前一天晚上20点前取消。");
            msgTemplateContents.add(firstMap);

            Map<String,String> k1Map = new HashedMap();
            k1Map.put("keyword","姓名");
            k1Map.put("note","");
            k1Map.put("value",order.getUserName());
            msgTemplateContents.add(k1Map);

            Map<String,String> k2Map = new HashedMap();
            k2Map.put("keyword","卡号");
            k2Map.put("note","");
            k2Map.put("value",order.getMedicalCardNo());
            msgTemplateContents.add(k2Map);

            Map<String,String> k3Map = new HashedMap();
            k3Map.put("keyword","科室");
            k3Map.put("note","");
            k3Map.put("value",order.getDeptName());
            msgTemplateContents.add(k3Map);

            Map<String,String> k4Map = new HashedMap();
            k4Map.put("keyword","医生");
            k4Map.put("note","");
            k4Map.put("value",order.getDoctorName());
            msgTemplateContents.add(k4Map);

            String scheduleTime = order.getScheduleTime();
            if (scheduleTime != null && scheduleTime.length() > 10) {
                scheduleTime = scheduleTime.substring(0, 10);
            }
            scheduleTime += " " + extraParams.get("begin_time");

            Map<String,String> k5Map = new HashedMap();
            k5Map.put("keyword","预约时间");
            k5Map.put("note","");
            k5Map.put("value",scheduleTime);
            msgTemplateContents.add(k5Map);

            contentMap.put("msgTemplateContents", msgTemplateContents);

            List<Map<String,String>> msgTemplateFunctions = new ArrayList<>();
            Map<String,String> funcMap = new HashedMap();
            funcMap.put("functionCode","location='" +url + "'" );
            funcMap.put("functionName","点击查看预约详情");
            msgTemplateFunctions.add(funcMap);

            contentMap.put("msgTemplateFunctions",msgTemplateFunctions);
            yytMap.put("msg_content",JsonUtils.toJsonString(contentMap));
            yytMap.put("created_time",DateUtils.dateToString(new Date()));

            Response messageResponse = MessageService.callHumpFromInternal("yyt.message.messagehistory.add",JsonUtils.toJsonString(yytMap));
            logger.info("订单号" + order.getOrderNo() + ", 调用message模块,yyt.message.messagehistory.add request={}，response={}",
                    JsonUtils.toJsonString(yytMap),JsonUtils.toJsonString(messageResponse));

        }
    }

    /**
     * 转换为锁号接口对外返回的对象
     * @param order
     * @return
     */
    private LockRegInfoVoOut parseLocRegInfoVoOut(OrderExtVo order) {
        Map<String, String> extraParamsMap = JsonUtils.parseObject(order.getExtraParams(), Map.class);

        LockRegInfoVoOut lockRegInfoVoOut = new LockRegInfoVoOut();

        lockRegInfoVoOut.setOrderNo(order.getOrderNo());
        lockRegInfoVoOut.setDeptCode(order.getDeptCode());
        lockRegInfoVoOut.setDeptName(order.getDeptName());
        lockRegInfoVoOut.setDoctorCode(order.getDoctorCode());
        lockRegInfoVoOut.setDoctorName(order.getDoctorName());
        lockRegInfoVoOut.setCreatedTime(order.getCreatedTime());
        lockRegInfoVoOut.setIsInsurance(order.getIsInsurance());
        lockRegInfoVoOut.setRegCategory(extraParamsMap.get("reg_category"));
        lockRegInfoVoOut.setRegFee(ObjectParser.toInteger(extraParamsMap.get("reg_fee")));
        lockRegInfoVoOut.setTreatFee(ObjectParser.toInteger(extraParamsMap.get("treat_fee")));

        lockRegInfoVoOut.setOnlinePaymentControl(order.getOnlinePaymentControl());
        lockRegInfoVoOut.setPayTimeoutTime(ObjectParser.toInteger(extraParamsMap.get("pay_timeout_time")));

        if(1 == order.getIsInsurance()) {
            Map<String,Object> lockOutMap = new HashedMap();
            lockOutMap.put("insurance_order_no",extraParamsMap.get("insurance_order_no"));
            lockOutMap.put("medical_org_code",extraParamsMap.get("medical_org_code"));
            lockOutMap.put("operator_code",extraParamsMap.get("operator_code"));
            lockOutMap.put("operator_name",extraParamsMap.get("operator_name"));
            lockOutMap.put("cancel_serial_no",extraParamsMap.get("cancel_serial_no"));
            lockOutMap.put("cancel_bill_no",extraParamsMap.get("cancel_bill_no"));
            lockRegInfoVoOut.setExtraParams(JsonUtils.toJsonString(lockOutMap));
        }
        return lockRegInfoVoOut;
    }

    /** 挂号解锁接口
     * yyt.register.reg.info.unlock --> yyt.register.reg.record.unlock
     * @param data
     * @param sessionId
     * @return
     * @throws Exception
     */
    public Response unlockRegRecord(String data, String sessionId) throws Exception {
        Response response = new Response();
        logger.info("挂号解锁--->method:unlockRegRecord,data:" + data + "！");
        Map<String,Object> requestVo = JsonUtils.parseObject(data, Map.class);
        String orderNo = (String) requestVo.get("order_no");

        //对外工具扩展需要，适应旧平台的查询(旧平台在新库不能实时查询到数据，所以要前端传入相关的数据，最后直接调前置机接口)
        String hospitalCode = (String) requestVo.get("hospital_code");
        String branchCode = (String) requestVo.get("branch_code");
        String hisOrderNo = (String) requestVo.get("his_order_no");
        String cancelReason = (String) requestVo.get("cancel_reason");
        String regType = (String) requestVo.get("reg_type");
        String channelType = (String) requestVo.get("channel_type");//渠道：0-新平台 1-旧平台， 默认为新平台

        OrderExtVo vo = new OrderExtVo();
        if("1".equals(channelType)){
            //旧平台订单处理逻辑
            if(StringUtils.isBlank(hospitalCode)){
                response.setResultCodeAndMessage("-1","hospital_code不能为空");
                return response;
            }
            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("-1","order_no不能为空");
                return response;
            }
            if(StringUtils.isBlank(hisOrderNo)){
                response.setResultCodeAndMessage("-1","his_order_no不能为空");
                return response;
            }
            if(StringUtils.isBlank(regType)){
                response.setResultCodeAndMessage("-1","reg_type不能为空");
                return response;
            }

            vo.setOrgCode(hospitalCode);
            vo.setBranchCode(branchCode);
            vo.setOrderNo(orderNo);
            vo.setHisOrderNo(hisOrderNo);

        }else{
            //新平台订单的处理逻辑保持不变
            if(StringUtils.isBlank(orderNo)){
                response.setResultCodeAndMessage("-1","order_no不能为空");
                return response;
            }

            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("order_no", orderNo);
            dataMap.put("order_type", OrderExtVo.ORDER_TYPE_REGISTER);
            logger.info("unlockRegRecord, yyt.base.order.by.orderno.get request=" + JSON.toJSONString(dataMap));
            Response ordResponse = BaseService.callUnderlineFromInternal(sessionId, "yyt.base.order.by.orderno.get",
                    JsonUtils.toJsonString(dataMap));
            logger.info("unlockRegRecord, yyt.base.order.by.orderno.get ordResponse=" + JSON.toJSONString(ordResponse));
            if (!"0".equals(ordResponse.getResultCode())) {
                response.setResultCodeAndMessage(ordResponse.getResultCode(), ordResponse.getResultMessage());
                return response;
            }
            vo = JsonUtils.parseObject(ordResponse.getResult(), OrderExtVo.class);

            if(vo == null){
                response.setResultCodeAndMessage("3002", "订单不存在。");
                return response;
            }
            if(vo.getOrderStatus() == OrderExtVo.ORDER_STATUS_CANCEL){
                response.setResultCodeAndMessage("3101","订单已是取消状态，无需解锁");
                return response;
            }

            if(vo.getPayStatus() > OrderExtVo.ORDER_PAY_STATUS_ACCESS){
                response.setResultCodeAndMessage("3101","订单不是未支付状态，不能解锁");
                return response;
            }

            //医保结算订单，先进行医保退款
            if(vo.getInsuranceSettleFlag() != null && vo.getInsuranceSettleFlag() == 1) {
                Response refundResp = regInsuranceService.refundRegInsurance("{\"order_no\":\"" + vo.getOrderNo() + "\"}", sessionId);
                if (!"0".equals(refundResp.getResultCode())) {
                    logger.info("unlockRegRecord 医保退款失败，解锁不成功");
                    return refundResp;
                }
            }

            regType = RegUtil.getRegType(vo.getScheduleTime());
            cancelReason = null;
        }

        CancelRegisterVo cancelRegisterVo = new CancelRegisterVo();
        cancelRegisterVo.setHospitalCode(vo.getOrgCode());
        cancelRegisterVo.setBranchCode(vo.getBranchCode());
        cancelRegisterVo.setHisOrdNum(vo.getHisOrderNo());
        cancelRegisterVo.setCancelTime(DateUtils.dateToString(new Date()));
        cancelRegisterVo.setYytOrdNum(vo.getOrderNo());
        cancelRegisterVo.setRegType(regType);
        cancelRegisterVo.setCancelReason(cancelReason);
        Map<String,String> extMap = new HashedMap();
//        extMap.put("pat_card_type",String.valueOf(vo.getMedicalCardType()));
        extMap.put("pat_card_no",vo.getMedicalCardNo());//福田中医院需求
        Map<String, Object> extraParams = JsonUtils.parseObject(vo.getExtraParams(), Map.class);
        if(extraParams.get("work_id") != null) {
            extMap.put("work_id", (String) extraParams.get("work_id"));
        }
        if(extraParams.get("serial_num") != null) {
            extMap.put("serial_num", (String) extraParams.get("serial_num"));
        }

        cancelRegisterVo.setExtendParams(JsonUtils.toJsonString(extMap));
        ResCommon resCommon = HisifaceService.getHisifaceClient().cancelRegister(cancelRegisterVo);
        logger.info("unlockRegRecord  his response=" + JSON.toJSONString(resCommon));
        if("0".equals(resCommon.getResultCode())){
            vo.setOrderStatusCancel();//解锁后状态改成7 取消
            vo.setUpdateTime(DateUtils.getDatetime());
            BaseService.callUnderlineFromInternal("", "yyt.base.order.update", JsonUtils.toJsonString(vo));
            response.setResultCodeAndMessage("0","解锁号源成功");
        }else {
            response.setResultCodeAndMessage(resCommon.getResultCode(),"解锁号源失败，请稍后再试");
        }

        return response;
    }

    /**
     * 设置医院返回的order信息设置record
     *
     */
    private void addHisOrderInfo(OrderRegisterVoResponse hisOrder, Map<String, Object> extraParamsMap, String regFee, String treatFee) {
        if(hisOrder == null){
            return ;
        }
//        String extendParams = hisOrder.getExtendParams();
        String realRegFee;
        String realTreatFee;
        if(hisOrder != null){
//            JSONObject hisExtend = JSONObject.parseObject(extendParams);
            if (StringUtils.isNotBlank(hisOrder.getRegFee())) {
                realRegFee = hisOrder.getRegFee();// hisExtend.getString("reg_fee");
                if(StringUtils.isBlank(regFee) || "0".equals(regFee)){//挂号费为零，更新为his返回的金额
                    regFee =  hisOrder.getRegFee();//hisExtend.getString("reg_fee");
                }
            } else {
                realRegFee = regFee ;
            }

            if (StringUtils.isNotBlank(hisOrder.getTreatFee())) {
                realTreatFee = hisOrder.getTreatFee();//hisExtend.getString("treat_fee");
                if(StringUtils.isBlank(treatFee) || "0".equals(treatFee)){//诊疗费为零，更新为his返回的金额
                    treatFee = hisOrder.getTreatFee();//hisExtend.getString("treat_fee");
                }
            } else {
                realTreatFee = treatFee ;
            }

            if(StringUtils.isNotBlank(hisOrder.getDesc())) {
                extraParamsMap.put("desc", hisOrder.getDesc());
            }
            String hisExtendParams = hisOrder.getExtendParams();
            if(StringUtils.isNotBlank(hisExtendParams)){
                JSONObject hisExtend = JSONObject.parseObject(hisExtendParams);
                extraParamsMap.put("cancel_serial_no",hisExtend.getString("cancel_serial_no"));
                extraParamsMap.put("cancel_bill_no",hisExtend.getString("cancel_bill_no"));
            }

        }else{
            realRegFee = regFee;
            realTreatFee = treatFee;
        }

        extraParamsMap.put("reg_fee",regFee);
        extraParamsMap.put("treat_fee",treatFee);
        extraParamsMap.put("real_reg_fee",realRegFee);
        extraParamsMap.put("real_treat_fee",realTreatFee);

    }


    /**
     * 校验是否重复订单
     * @param requestVo
     * @return
     */
    private  Map<String,Object> checkReInvoke(OrderRegisterVoRequest requestVo) {
        Map<String,Object> map = new HashedMap();
        boolean reInvoke = false;
        try {
            String rule = RegUtil.getRule( requestVo.getHospitalCode(), "IsRepeatOrder", "1");
            if ("1".equals(rule)){
                Map<String, Object> queryMap = new HashMap<>();
                queryMap.put("org_code", requestVo.getHospitalCode());
                queryMap.put("medical_card_no", requestVo.getPatCardNo());
                queryMap.put("medical_card_type", requestVo.getPatCardType());
                queryMap.put("dept_code", requestVo.getDeptCode());
                queryMap.put("doctor_code", requestVo.getDoctorCode());
                queryMap.put("pay_status", OrderExtVo.ORDER_PAY_STATUS_ACCESS);
                queryMap.put("order_status", OrderExtVo.ORDER_STATUS_CREATE);
                queryMap.put("is_insurance", requestVo.getIsInsurance());

                Response ordResponse = BaseService.callUnderlineFromInternal("",
                        "yyt.base.order.list.get", JsonUtils.toJsonString(queryMap));
//        logger.info("lockRegInfo, yyt.base.order.list ordResponse="+ JSON.toJSONString(ordResponse));
                if ("0".equals(ordResponse.getResultCode())) {
                    List<OrderExtVo> list = JsonUtils.parseArray(ordResponse.getResult(), OrderExtVo.class);
                    if (!CollectionUtils.isEmpty(list)) {
                        for(OrderExtVo order:list){
                            logger.info("checkReInvoke lasted order={}", JSON.toJSONString(order));
                            Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                            if (order.getScheduleTime().startsWith(requestVo.getScheduleDate()) &&
                                    requestVo.getBeginTime().equals(extraParams.get("begin_time"))
                                    && requestVo.getEndTime().equals(extraParams.get("end_time"))) {
                                reInvoke = true;
                                String payTimeout = (String) extraParams.get("pay_timeout_time");
                                if (StringUtils.isNotBlank(payTimeout)) {
                                    Calendar c = Calendar.getInstance();
                                    c.setTime(DateUtils.StringToDate(order.getCreatedTime()));
                                    long outtime = System.currentTimeMillis() - c.getTimeInMillis();
                                    if (outtime > (ObjectParser.toInteger(payTimeout) * 60000)) {
                                        //订单已超时未支付
                                        logger.info("checkReInvoke,订单已超时未支付,不判断成重复订单，orderNo= " + order.getOrderNo() + ",超时时间" + outtime);
                                        reInvoke = false;
                                    }
                                }
                                if(reInvoke){
                                    logger.info("checkReInvoke,重复订单，返回原订单orderNo= " + order.getOrderNo());
                                    map.put("reInvoke",reInvoke);
                                    map.put("order",order);
                                    return map;
                                }
                            }
                        }//for
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        map.put("reInvoke",reInvoke);
        return map;
    }

    /**
     * 校验挂号成功的 是否一个卡号同一天同一科室同一医生只能挂一次
     * @param requestVo
     * @return
     */
    private boolean checkOneTimeReg(OrderRegisterVoRequest requestVo) {
        boolean reInvoke = false;
        try {
            Map<String, Object> queryMap = new HashMap<>();
            queryMap.put("org_code", requestVo.getHospitalCode());
            queryMap.put("medical_card_no", requestVo.getPatCardNo());
            queryMap.put("dept_code", requestVo.getDeptCode());
            queryMap.put("doctor_code", requestVo.getDoctorCode());
            queryMap.put("order_status", OrderExtVo.ORDER_STATUS_SUCCESS);
            queryMap.put("order_type", OrderExtVo.ORDER_TYPE_REGISTER);
            queryMap.put("begin_schedule_time", requestVo.getScheduleDate());
            queryMap.put("end_schedule_time", requestVo.getScheduleDate() + " 23:59:59");

            Response ordResponse = BaseService.callUnderlineFromInternal("",
                    "yyt.base.order.list.get", JsonUtils.toJsonString(queryMap));
//        logger.info("lockRegInfo, yyt.base.order.list ordResponse="+ JSON.toJSONString(ordResponse));
            if ("0".equals(ordResponse.getResultCode())) {
                List<OrderExtVo> list = JsonUtils.parseArray(ordResponse.getResult(), OrderExtVo.class);
                if (!CollectionUtils.isEmpty(list)) {
                    for(OrderExtVo order:list){
                        logger.info("checkOneTimeReg lasted order={}", JSON.toJSONString(order));
                        Map<String, Object> extraParams = JsonUtils.parseObject(order.getExtraParams(), Map.class);
                        if (order.getScheduleTime().startsWith(requestVo.getScheduleDate()) &&
                                requestVo.getBeginTime().equals(extraParams.get("begin_time"))
                                && requestVo.getEndTime().equals(extraParams.get("end_time"))) {
                          return true;
                        }
                    }//for
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return reInvoke;
    }

}
